package nl.rainbowsheep.reisorg.cust.site.controller;

import com.tunyk.currencyconverter.api.CurrencyNotSupportedException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.Principal;
import nl.rainbowsheep.reisorg.cust.site.controller.helper.ConvertCurrency;
import nl.rainbowsheep.reisorg.cust.site.service.TripBookingService;
import nl.rainbowsheep.reisorg.cust.site.viewmodel.TripBookingViewmodel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/tripbooking")
public class TripBookingController {

    @Autowired
    TripBookingService tripBookingService;

    @RequestMapping(value = {"", "/"})
    public ModelAndView redirectToIndex() {
        ModelAndView mav = new ModelAndView("redirect:tripbooking/index");
        return mav;
    }

    @RequestMapping("/index")
    public ModelAndView index(@CookieValue("currency") String cookieCur, Principal principal) throws CurrencyNotSupportedException {
        ModelAndView mav = new ModelAndView();
        String username = principal.getName();
        TripBookingViewmodel[] tripbookings = tripBookingService.getByUsername(username);
        if (tripbookings.length > 0) {
            ConvertCurrency converter = null;
            for (TripBookingViewmodel tripviewmodel : tripbookings) {
            converter = new ConvertCurrency(tripviewmodel.getTripViewmodel().getTrip().getPrice().floatValue(), cookieCur);
            float price = converter.getAmount();
            tripviewmodel.getTripViewmodel().getTrip().setPrice(new BigDecimal(price).setScale(2, RoundingMode.CEILING));
            }
            mav.addObject("sign", converter.getCurrencySign());
        }
//        ModelAndView mav = new ModelAndView("tripbooking/index");
        mav.addObject("tripbookings", tripbookings);
        return mav;
    }
}
